<!--上架或修改上架范围-->
<template>
  <el-dialog
    :title="launchOrModifyType === 'launch' ? '上架固件版本' : '修改上架'"
    :visible.sync="launchOrModifyVisible"
    width="628px"
    :before-close="handleClose"
    :close-on-click-modal="false">
    <el-form ref="form" :rule="rules" :model="form" label-width="160px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="固件名称" prop="name">
            <span>{{ form.name }}</span>
          </el-form-item>
          <el-form-item label="固件版本" prop="version">
            <span>{{ form.version }}</span>
          </el-form-item>
          <el-form-item label="版本说明" prop="description">
            <span>{{ form.description }}</span>
          </el-form-item>
          <el-form-item label="设置允许使用范围" prop="isLaunch">
            <el-radio-group v-model="form.allowedScope">
              <el-radio :label="0">不限范围</el-radio>
              <el-radio :label="1">限定范围</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="form.allowedScope !== 1" class="desc">
            <span v-if="launchOrModifyType === 'launch'">支持所有产品ID（PID）可使用该固件版本，用于固件升级</span>
            <span v-else>支持所有客户和PID可使用该固件版本，用于产品复制、OEM和固件升级</span>
          </div>
          <div v-else class="table">
            <div class="table-header">
              <div>已授权范围</div>
              <el-button type="primary" size="14" :disabled="isLastRowEmpty" @click="handleAddLine">添加</el-button>
            </div>
            <el-table
              :data="form.productList"
              style="width: 100%;border: 1px solid #e6e6e6;"
              size="medium"
              border>
              <el-table-column prop="whiteType" label="白名单类型" />
              <el-table-column prop="productId" label="产品ID" />
              <el-table-column prop="customerName" label="客户名称" />
              <el-table-column label="操作" width="100">
                <template slot-scope="scope">
                  <el-button type="text" size="14" @click="handleDelete(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-form ref="searchForm" :inline="true" class="search-form">
              <el-col :span="24">
                <el-form-item>
                  <el-select v-model="formSearch.type">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-input v-model="formSearch.productId" clearable />
                </el-form-item>
                <el-button
                  type="primary"
                  size="14"
                  :disabled="!form.productList.length || !!form.productList[form.productList.length - 1].productId"
                  @click="handleAddProductCheck()">添加</el-button>
              </el-col>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="14" @click="handleClose">取消</el-button>
      <el-button type="primary" size="14" @click="handleSubmit">确认上架</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addProductCheck, getFirmwareVersionDetail, modifyFirmwareVersionRange } from "@/api/product/firmware"
export default {
  name: "addFirmwareDialog",
  props: {
    launchOrModifyType: {
      type: String,
      default: 'launch' // launch 新建 modify 编辑
    },
    queryVersionList: {
      type: Function,
      default: () => { }
    },
    launchRowsData: {
      type: Object,
      default: () => { }
    }
  },
  data() {
    return {
      launchOrModifyVisible: false, // 弹窗是否显示
      form: {
        name: '', // 固件名称
        version: '', // 固件版本
        description: '', // 版本说明
        allowedScope: 0, // 允许使用范围 0 不限范围 1 限定范围
        productList: [] // 已授权范围列表
      },
      options: [
        { value: 'productId', label: '产品ID（PID）' },
        { value: 'whiteListType', label: '白名单类型' },
        { value: 'customerName', label: '客户名称' }
      ],
      formSearch: {
        type: 'productId',
        productId: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入固件名称', trigger: 'blur' }
        ],
        version: [
          { required: true, message: '请输入固件版本', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    isLastRowEmpty() {
      if (this.form.productList.length === 0) return false
      const last = this.form.productList[this.form.productList.length - 1]
      return !last.whiteType && !last.productId && !last.customerName
    }
  },
  watch: {
    launchOrModifyVisible(val) {
      if (val) {
        this.getFirmwareVersionDetail()
      } else {
      // 关闭时可清理表单
      this.$refs.form?.resetFields()
      }
    }
  },
  created() {},
  methods: {
    // 新建固件弹窗关闭
    handleClose() {
      this.launchOrModifyVisible = false
      this.$refs.form.resetFields()
    },
    // 获取固件上架详情
    getFirmwareVersionDetail() {
      const params = {
        firmwareVersionId: this.launchRowsData.id
      }
      getFirmwareVersionDetail(params).then(res => {
        this.form = res.data.data
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 添加表格行
    handleAddLine() {
      this.form.productList.push({
        whiteType: '',
        productId: '',
        customerName: ''
      })
    },
    // 添加产品校验
    handleAddProductCheck() {
      if (!this.formSearch.productId) {
        this.$message.warning('请输入搜索内容')
        return
      }
      const params = {
        productId: this.formSearch.productId
      }
      addProductCheck(params).then(res => {
        const newData = res.data.data
        // 检查是否已存在相同的产品ID或客户名称
        const exists = this.form.productList.some(item =>
          (item.productId && item.productId === newData.productId)
        )
        if (exists) {
          this.$message.warning('该产品ID或客户名称已存在')
          return
        }
        // 修改最后一行
        this.$set(this.form.productList, this.form.productList.length - 1, newData)
        this.formSearch.productId = ''
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 删除
    handleDelete(index) {
      this.form.productList.splice(index, 1)
    },
    // 确认上架
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            firmwareVersionId: this.launchRowsData.id,
            allowedScope: this.form.allowedScope,
            productList: this.form.allowedScope === 1 ? this.form.productList : []
          }
          modifyFirmwareVersionRange(params).then(res => {
            this.$message.success(this.launchOrModifyType === 'launch' ? '固件上架成功' : '修改上架成功')
            this.queryVersionList()
            this.launchOrModifyVisible = false
          }).catch(err => {
            this.$message.error(err.message)
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.desc {
  width: 100%;
  height: 130px;
  border: 1px solid #e6e6e6;
  text-align: center;
  padding: 15px 0;
}

.table {
   border: 1px solid #e6e6e6;
   padding: 10px;

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .search-form {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 10px;
  }
}
</style>

